package com.dq.health.utils.data;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class TreeUtil {
	public static final String ROOT_NODE_ID = "-1";

	public static <T> Tree<T> make(Set<Node<T>> nodes) {
		Node<T> root = new Node<>();
		root.setNodeId(ROOT_NODE_ID);

		Map<String, Node<T>> map = new HashMap<>();
		map.put(ROOT_NODE_ID, root);

		for (Node<T> node : nodes) {
			map.put(node.getNodeId(), node);
		}

		for (Node<T> node : nodes) {
			HashSet<String> parentNodeIds = node.getParentNodeIds();

			// 第一层级节点
			if (parentNodeIds == null || parentNodeIds.size() == 0) {
				node.setParentNodeIds(SetUtil.toSet(ROOT_NODE_ID));
				root.addChildNode(node);
				continue;
			}

			for (String parentNodeId : parentNodeIds) {
				Node<T> parentNode = map.get(parentNodeId);

				if (parentNode == null) {
					continue;
				}

				if (parentNode.getIsAddChild()) {
					parentNode.addChildNode(node);
				}
			}
		}

		Tree<T> tree = new Tree<>(root);
		return tree;
	}
}
